package com.kaifamiao.listener;

import org.tinylog.Logger;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

@WebListener
public class SessionAttributeListener implements HttpSessionAttributeListener {

    // 向当前请求关联的会话对象中成功添加新属性时调用此方法
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        HttpSession session = event.getSession();
        String name = event.getName();
        Object value = event.getValue();
        Logger.trace("向{}会话中成功添加{}属性(取值是{})", session.getId(), name, value );
    }

    // 成功替换当前请求关联的会话对象中的已有属性时调用此方法
    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        HttpSession session = event.getSession();
        String name = event.getName();
        Object old = event.getValue();
        Object value = session.getAttribute(name);
        Logger.trace("成功替换{}会话中{}属性(原值: {}, 新值: {})", session.getId(), name, old, value );
    }

    // 从当前请求关联的会话对象中成功删除属性时调用此方法
    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        HttpSession session = event.getSession();
        String name = event.getName();
        Object value = event.getValue();
        Logger.trace("从{}会话中成功删除{}属性(取值是{})", session.getId(), name, value );
    }

}
